#encoding: utf8
import urllib2
# 1. 导入Python SSL处理模块
import ssl
from pyquery import PyQuery as pyq
import redis
import logging
import time
rds = redis.Redis(host='127.0.0.1', port=6379,db=0)

def search_ip(ip):
    # url = "https://www.boip.net/ipv4/47.95.47.253"
    url = "https://www.boip.net/ipv4/%s" %(ip)
    ret_list = []
    context = ssl._create_unverified_context()
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
    request = urllib2.Request(url, headers = headers)

    try:
        response = urllib2.urlopen(request, context = context)
        html_page = response.read()
        jq = pyq(html_page)
        data_div = jq("div.ipaddr")
        data_items = data_div("div.x")
        for item in data_items:
            title = pyq(item)("div.l").text()
            content = pyq(item)("div.r").text()

            ret_list.append((title, content))
    except Exception, e:
        pass

    return ret_list

def search_dns(ip):
    uri = rds.get("DNS_%s" %(ip))
    return uri
    

def ip2host(ip):
    uri = search_dns(ip)
    if uri:
        return uri
    else:
        return ip
        # res = search_ip(ip)
        # for (title, content) in res:
        #     # title = item[0]
        #     # content = item[1]
        #     logger.info("%s: %s"%(title, content))

if __name__ == '__main__':

    fileHandler = logging.FileHandler(filename = "ip_result.log", mode="w")
    fmt = '%(asctime)s %(levelname)s %(message)s'
    formatter = logging.Formatter(fmt)
    fileHandler.setFormatter(formatter)

    consoleHandler = logging.StreamHandler()
    consoleHandler.setFormatter(formatter)
    logging.getLogger('val').addHandler(fileHandler)
    logging.getLogger('val').addHandler(consoleHandler)
    logger = logging.getLogger('val')
    logger.setLevel(logging.DEBUG)

    rds = redis.Redis(host='127.0.0.1', port=6379,db=0)
    store_keys = rds.keys()
    for key in store_keys:
        split_char_idx = key.find("->")
        if split_char_idx != -1:
            dstip = key[split_char_idx+2:]
            ip2host(dstip)

        # time.sleep(5)
            
